#!/usr/bin/env bash

MY_DIR="$( cd "$( dirname $0)" && pwd )"
. "$MY_DIR/config.sh"
. "$MY_DIR/log.sh"

TRANSFMT="$BIN_DIR/transfmt"
# FFMPEG="$BIN_DIR/ffmpeg"
FFMPEG="/usr/bin/ffmpeg"
ONCE=0

while [[ $# -gt 0 ]]
do
    key="$1"
    case $key in
        --once)
            ONCE=1
        ;;
        *)
            echo "unknown option $key"
            exit -1
        ;;
    esac
    shift # past argument or value
done

log_init "scanner.log"

while true; do
    mkdir -p "$LOG_DIR"
    mkdir -p "$INPUT_DIR"
    mkdir -p "$OUTPUT_DIR"
    mkdir -p "$HISTORY_DIR"
    mkdir -p "$RECORD_ON_DEMAND_DIR"
    mkdir -p "$TEMP_DIR"

    ENDC_FILES=$(find "$INPUT_DIR" -name endc.info)
    for ENDC in $ENDC_FILES; do
        ENDC_DIR=$( dirname $ENDC )
        ENDC_RELATIVE_PATH=$( realpath --relative-to $INPUT_DIR $ENDC_DIR )
        TLV_FILES=$( find "$ENDC_DIR" -name "*.tlv" | grep -v extract)

        ALL_OKAY=1
        for TLV in $TLV_FILES; do
            log_info "|full record| tlv=$TLV"
            TLV_LOG=${TLV}.log
            TLV_RELATIVE_PATH=$( realpath --relative-to $INPUT_DIR $( dirname "$TLV" ) )
            mkdir -p "$OUTPUT_DIR/$TLV_RELATIVE_PATH"
            TRANSFMT_OUTPUT=$( ${TRANSFMT} -v -g -i ${TLV_LOG} -o ${TLV} "$OUTPUT_DIR/$TLV_RELATIVE_PATH/$(basename ${TLV%.*})" 2>&1 )
            TRANSFMT_ERROR=$?
            OUTPUT_FILE=$( echo "$TRANSFMT_OUTPUT" | grep "output filename = " | awk -F ' = ' '{print $2;}' )
            OUTPUT_TS_FILE="${OUTPUT_FILE%.*}.ts"
            log_debug "|full record| output=$OUTPUT_FILE"
            log_debug "|full record| ts=$OUTPUT_TS_FILE"

            if [[ ${TRANSFMT_ERROR} -ne 0 ]]; then
                log_error "|full record| trans-format failed"
                ALL_OKAY=0
            else
                log_info "|full record| trans-format success"
            fi
            # send copy to merge
            mkdir -p "$MERGE_IN_DIR/$TLV_RELATIVE_PATH/"
            cp -f "$OUTPUT_FILE" "$MERGE_IN_DIR/$TLV_RELATIVE_PATH/"
            cp -f "$OUTPUT_TS_FILE" "$MERGE_IN_DIR/$TLV_RELATIVE_PATH/"
            log_info "|full record| copy to $MERGE_IN_DIR/$TLV_RELATIVE_PATH/"
        done
        # send endc to merge-in
        mkdir -p "$MERGE_IN_DIR/$ENDC_RELATIVE_PATH"
        cp -f "$ENDC" "$MERGE_IN_DIR/$ENDC_RELATIVE_PATH/"
        touch "$MERGE_IN_DIR/$ENDC_RELATIVE_PATH/merge.this.directory"

        for TLV in ${TLV_FILES}; do
            TLV_LOG=${TLV}.log
            TLV_RELATIVE=$( realpath --relative-to ${INPUT_DIR} $( dirname "$TLV" ) )

            # then move to history
            if [[ ${ALL_OKAY} -eq 1 ]]; then
                TLV_HISTORY_DIR="${HISTORY_DIR}/success/${TLV_RELATIVE}"
                mkdir -p ${TLV_HISTORY_DIR}
                mv -f ${TLV} ${TLV_HISTORY_DIR}
                mv -f ${TLV_LOG} ${TLV_HISTORY_DIR}
            else
                TLV_HISTORY_DIR="${HISTORY_DIR}/failure/${TLV_RELATIVE}"
                mkdir -p ${TLV_HISTORY_DIR}
                mv -f ${TLV} ${TLV_HISTORY_DIR}
                mv -f ${TLV_LOG} ${TLV_HISTORY_DIR}
            fi
        done
        mv ${ENDC} ${OUTPUT_DIR}/${ENDC_RELATIVE_PATH}/
        if [[ "${ENDC_DIR}" != "${INPUT_DIR}" ]]; then
            rm -rf ${ENDC_DIR}
        fi
    done

    # sample cmd file
    # SRC_FILE="./fake1.tlv"
    # DST_FORMAT="jpg"
    # if DST_FORMAT is not set, it will default to what transfmt choosed
    CMD_FILES=$(find ${INPUT_DIR} -name "*.transfmt")
    for c in $CMD_FILES; do
        unset SRC_FILE
        unset DST_FORMAT
        source $c
        log_info "|on-demand| tlv=$SRC_FILE"
        if [[ -z ${SRC_FILE} ]]; then
            RELATIVE_PATH="$( realpath --relative-to ${INPUT_DIR} $( dirname ${c} ) )"
            FAILURE_DIR="${HISTORY_DIR}/failure/${RELATIVE_PATH}"
            mkdir -p ${FAILURE_DIR}
            mv -f $c ${FAILURE_DIR}
            log_error "|on-demand| invalid job: no tlv"
        elif [[ -z ${DST_FORMAT} ]]; then
            RELATIVE_PATH="$( realpath --relative-to ${INPUT_DIR} $( dirname ${c} ) )"
            SRC_FILE="$INPUT_DIR/$SRC_FILE"
            FAILURE_DIR="${HISTORY_DIR}/failure/${RELATIVE_PATH}"
            mkdir -p ${FAILURE_DIR}
            mv -f $c ${FAILURE_DIR}
            mv -f ${SRC_FILE} ${FAILURE_DIR}
            mv -f "${SRC_FILE%.*}.ctx" "$FAILURE_DIR"
            log_error "|on-demand| invalid job: no format"
        else
            #RELATIVE_PATH="$( realpath --relative-to ${INPUT_DIR} $( dirname ${SRC_FILE} ) )"
            RELATIVE_PATH="$( dirname "$SRC_FILE" )"
            SRC_FILE="$INPUT_DIR/$SRC_FILE"
            BASE_NAME=$( basename ${SRC_FILE})
            mkdir -p ${TEMP_DIR}/${RELATIVE_PATH}
            TRANSFMT_OUTPUT=$( ${TRANSFMT} -v -g ${SRC_FILE}.log -i ${SRC_FILE} -o ${TEMP_DIR}/${RELATIVE_PATH}/${BASENAME%.*} 2>&1)
            TRANSFMT_ERROR=$?
            INTER_FILE=$( echo "$TRANSFMT_OUTPUT" | grep "output filename = " | awk -F ' = ' '{print $2;}' )
            log_info "|on-demand| output=$INTER_FILE"
            INTER_TS_FILE="${INTER_FILE%.*}.ts"
            INTER_FILE_EXT=$( basename "$INTER_FILE")
            INTER_FILE_EXT=${INTER_FILE_EXT##*.}
            if [[ ${TRANSFMT_ERROR} -ne 0 ]]; then
                FAILURE_DIR="${HISTORY_DIR}/failure/${RELATIVE_PATH}/"
                # make archives
                mkdir -p ${FAILURE_DIR}
                mv -f ${SRC_FILE} ${FAILURE_DIR}
                mv -f ${SRC_FILE}.log* ${FAILURE_DIR}
                mv -f "${SRC_FILE%.*}.ctx" ${FAILURE_DIR}
                mv -f $c ${FAILURE_DIR}
                # cleanup failure output
                rm -f "$INTER_FILE"
                rm -f "$INTER_TS_FILE"
                log_error "|on-demand| trans-format failed"
                continue
            else
                SUCCESS_DIR="${HISTORY_DIR}/success/${RELATIVE_PATH}/"
                mkdir -p ${SUCCESS_DIR}
                mv -f ${SRC_FILE} ${SUCCESS_DIR}
                mv -f ${SRC_FILE}.log* ${SUCCESS_DIR}
                cp -f "${SRC_FILE%.*}.ctx" ${SUCCESS_DIR}
                mv -f $c ${SUCCESS_DIR}
                log_info "|on-demand| trans-format success"
            fi
            # todo grep this from transfmt output
            #INTER_FILE=${TEMP_DIR}/${RELATIVE_PATH}/${BASE_NAME%.*}.mkv
            if [[ "${DST_FORMAT}" == "jpg" ]]; then
                JPG_FILE=${TEMP_DIR}/${RELATIVE_PATH}/${BASE_NAME%.*}.jpg
                log_info "|on-demand| jpg=$JPG_FILE"
                ${FFMPEG} -y -i ${INTER_FILE} -vframes 1 -vcodec jpeg2000 -f mjpeg ${JPG_FILE}
                if [[ $? -ne 0 ]]; then
                    FAILURE_DIR="${HISTORY_DIR}/failure/${RELATIVE_PATH}/"
                    mkdir -p "$FAILURE_DIR"
                    mv -f "$INTER_FILE" "$FAILURE_DIR"
                    mv -f "$INTER_TS_FILE" "$FAILURE_DIR"
                    mv -f "${SRC_FILE%.*}.ctx" "$SUCCESS_DIR"
                    rm -f "$JPG_FILE"
                    log_error "|on-demand| $INTER_FILE_EXT->jpg failed"
                else
                    SUCCESS_DIR="${HISTORY_DIR}/success/${RELATIVE_PATH}/"
                    mkdir -p "${SUCCESS_DIR}"
                    cp -f "$INTER_FILE" "$SUCCESS_DIR"
                    cp -f "$INTER_TS_FILE" "$SUCCESS_DIR"
                    cp -f "${SRC_FILE%.*}.ctx" "$SUCCESS_DIR"
                    mkdir -p ${RECORD_ON_DEMAND_DIR}/${RELATIVE_PATH}/
                    mv -f "$JPG_FILE" "$RECORD_ON_DEMAND_DIR/$RELATIVE_PATH/"
                    mv -f "$INTER_TS_FILE" "$RECORD_ON_DEMAND_DIR/$RELATIVE_PATH/"
                    rm -f "$INTER_FILE"
                    mv -f "${SRC_FILE%.*}.ctx" "${RECORD_ON_DEMAND_DIR}/${RELATIVE_PATH}/"
                    log_info "|on-demand| $INTER_FILE_EXT->jpg success"
                fi
            elif [[ "${DST_FORMAT}" == "wav" ]]; then
                WAV_FILE=${TEMP_DIR}/${RELATIVE_PATH}/${BASE_NAME%.*}.wav
                log_info "|on-demand| wav=$WAV_FILE"
                ${FFMPEG} -y -i ${INTER_FILE} -vn ${WAV_FILE}
                if [[ $? -ne 0 ]]; then
                    FAILURE_DIR="${HISTORY_DIR}/failure/${RELATIVE_PATH}/"
                    mkdir -p ${FAILURE_DIR}
                    mv -f "$INTER_FILE" "$FAILURE_DIR"
                    mv -f "$INTER_TS_FILE" "$FAILURE_DIR"
                    mv -f "${SRC_FILE%.*}.ctx" "$FAILURE_DIR"
                    rm -f "$WAV_FILE"
                    log_error "|on-demand| $INTER_FILE_EXT->wav failed"
                else
                    SUCCESS_DIR="${HISTORY_DIR}/success/${RELATIVE_PATH}/"
                    mkdir -p ${SUCCESS_DIR}
                    cp -f "$INTER_FILE" "$SUCCESS_DIR"
                    cp -f "$INTER_TS_FILE" "$SUCCESS_DIR"
                    cp -f "${SRC_FILE%.*}.ctx" "$SUCCESS_DIR"
                    mkdir -p "$RECORD_ON_DEMAND_DIR/$RELATIVE_PATH/"
                    mv -f "$WAV_FILE" "$RECORD_ON_DEMAND_DIR/$RELATIVE_PATH/"
                    mv -f "$INTER_TS_FILE" "$RECORD_ON_DEMAND_DIR/$RELATIVE_PATH/"
                    rm -f "$INTER_FILE"
                    mv -f "${SRC_FILE%.*}.ctx" "$RECORD_ON_DEMAND_DIR/$RELATIVE_PATH/"
                    log_info "|on-demand| $INTER_FILE_EXT->wav success"
                fi
            elif [[ "$DST_FORMAT" == "$INTER_FILE_EXT" ]]; then
                SUCCESS_DIR="$HISTORY_DIR/success/$RELATIVE_PATH/"
                mkdir -p "$SUCCESS_DIR"
                cp -f "$INTER_FILE" "$SUCCESS_DIR"
                cp -f "$INTER_FILE" "$SUCCESS_DIR"
                cp -f "${SRC_FILE%.*}.ctx" "$SUCCESS_DIR"
                mkdir -p "$RECORD_ON_DEMAND_DIR/$RELATIVE_PATH/"
                mv -f "$INTER_FILE" "$RECORD_ON_DEMAND_DIR/$RELATIVE_PATH/"
                mv -f "$INTER_TS_FILE" "$RECORD_ON_DEMAND_DIR/$RELATIVE_PATH/"
                mv -f "${SRC_FILE%.*}.ctx" "${RECORD_ON_DEMAND_DIR}/${RELATIVE_PATH}/"
                log_info "|on-demand| $INTER_FILE_EXT->$DST_FORMAT success"
            elif [[ "$DST_FORMAT" == "mkv" ]]; then
                MKV_FILE=${TEMP_DIR}/${RELATIVE_PATH}/${BASE_NAME%.*}.mkv
                log_info "|on-demand| mkv=$MKV_FILE"
                ${FFMPEG} -y -i ${INTER_FILE} -vcodec copy -acodec copy ${MKV_FILE}
                if [[ $? -ne 0 ]]; then
                    FAILURE_DIR="$HISTORY_DIR/failure/$RELATIVE_PATH/"
                    mkdir -p "$FAILURE_DIR"
                    mv -f "$INTER_FILE" "$FAILURE_DIR"
                    mv -f "$INTER_TS_FILE" "$FAILURE_DIR"
                    mv -f "${SRC_FILE%.*}.ctx" "$FAILURE_DIR"
                    rm -f "$MKV_FILE"
                    log_error "|on-demand| $INTER_FILE_EXT->mkv failed"
                else
                    SUCCESS_DIR="${HISTORY_DIR}/success/${RELATIVE_PATH}/"
                    mkdir -p "$SUCCESS_DIR"
                    cp -f "$INTER_FILE" "$SUCCESS_DIR"
                    cp -f "$INTER_TS_FILE" "$SUCCESS_DIR"
                    cp -f "${SRC_FILE%.*}.ctx" "$FAILURE_DIR"
                    mkdir -p "$RECORD_ON_DEMAND_DIR/${RELATIVE_PATH}/"
                    mv -f "$MKV_FILE" "$RECORD_ON_DEMAND_DIR/$RELATIVE_PATH/"
                    rm -f "$INTER_FILE"
                    mv -f "$INTER_TS_FILE" "$RECORD_ON_DEMAND_DIR/$RELATIVE_PATH/"
                    mv -f "${SRC_FILE%.*}.ctx" "$RECORD_ON_DEMAND_DIR/$RELATIVE_PATH/"
                    log_info "|on-demand| $INTER_FILE_EXT->mkv success"
                fi

            else
                FAILURE_DIR="${HISTORY_DIR}/failure/${RELATIVE_PATH}/"
                mkdir -p "$FAILURE_DIR"
                mv -f "$INTER_FILE" "$FAILURE_DIR"
                mv -f "$INTER_TS_FILE" "$FAILURE_DIR"
                mv -f "${SRC_FILE%.*}.ctx" "${RECORD_ON_DEMAND_DIR}/${RELATIVE_PATH}/"
                log_error "|on-demand| $INTER_FILE_EXT->$DST_FORMAT unknown"
                continue
            fi
        fi
    done

    find "$INPUT_DIR" -depth -type f -mtime +1 -delete
    find "$INPUT_DIR" -depth -type d -mtime +1 -empty -not -path "$INPUT_DIR" -delete

    find "$HISTORY_DIR" -type f -mtime +7 | xargs -n 1 rm -rf
    find "$HISTORY_DIR" -type d -mtime +7 -not -path "$HISTORY_DIR" | xargs -n 1 rm -rf
    find "$HISTORY_DIR" -depth -type d -mtime +1 -empty -not -path "$HISTORY_DIR" -delete

    find "$TEMP_DIR" -type f -mtime +7 | xargs -n 1 rm -rf
    find "$TEMP_DIR" -type d -mtime +7 -not -path "$TEMP_DIR" | xargs -n 1 rm -rf
    find "$TEMP_DIR" -depth -type d -mtime +1 -empty -not -path "$TEMP_DIR" -delete

    find "$RECORD_ON_DEMAND_DIR" -type f -mtime +7 | xargs -n 1 rm -rf
    find "$RECORD_ON_DEMAND_DIR" -type d -mtime +7 -not -path "$RECORD_ON_DEMAND_DIR" | xargs -n 1 rm -rf
    find "$RECORD_ON_DEMAND_DIR" -depth -type d -mtime +1 -empty -not -path "$RECORD_ON_DEMAND_DIR" -delete

    find "$LOG_DIR" -type f -mtime +7 | xargs -n 1 rm -rf
    find "$LOG_DIR" -type d -mtime +7 -not -path "$LOG_DIR" | xargs -n 1 rm -rf
    find "$LOG_DIR" -depth -type d -mtime +1 -empty -not -path "$LOG_DIR" -delete

    find "$OUTPUT_DIR" -type f -mtime +7 | xargs -n 1 rm -rf
    find "$OUTPUT_DIR" -type d -mtime +7 -not -path "$OUTPUT_DIR" | xargs -n 1 rm -rf
    find "$OUTPUT_DIR" -depth -type d -mtime +1 -empty -not -path "$OUTPUT_DIR" -delete

    find "$MERGE_IN_DIR" -depth -mtime +7 -not -path "$MERGE_IN_DIR" -delete
    find "$MERGE_OUT_DIR" -depth -mtime +7 -not -path "$MERGE_OUT_DIR" -delete

    if [[ ${ONCE} -eq 1 ]]; then
        echo "once"
        break
    fi

    sleep 1
    log_rotate_by_size
done
